/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package com.plian.system.controller.im;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.plian.Tools.*;
import com.plian.Tools.base.BaseController;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.annotation.LogOperation;
import com.plian.system.common.status.CustomCode;
import com.plian.system.config.Resubmit;
import com.plian.system.dto.im.BaseInvestmentPlanDTO;
import com.plian.system.entity.im.BaseInvestmentPlan;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.ObjResult;
import com.plian.system.model.R;
import com.plian.system.mybatis.search.SearchEntity;
import com.plian.system.mybatis.search.SearchParamEntiy;
import com.plian.system.mybatis.search.TokenSearch;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.mybatis.support.Query;
import com.plian.system.service.im.IBaseInvestmentPlanService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.im.BaseInvestmentPlanVO;
import com.plian.system.vo.im.InvestmentPlanSummaryVO;
import com.plian.system.vo.im.InvestmentUnitSummaryVO;
import com.plian.system.vo.report.ChartsVO;
import com.plian.system.wrapper.im.BaseInvestmentPlanWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 控制器
 *
 * @author
 * @since 2019-09-27
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("api/baseinvestmentplan")
@Api(value = "BaseInvestmentPlanController", tags = "投资计划 控制器")
public class BaseInvestmentPlanController extends BaseController {

	private IBaseInvestmentPlanService baseInvestmentPlanService;

	private FormWorkflowService formWorkflowService;

	private BaseInvestmentPlanWrapper baseInvestmentPlanWrapper;

	/**
	 * 详情
	 */
	@PostMapping("/detail")
	@ApiOperation(value = "详情", notes = "传入 BaseInvestmentPlan")
	public R<BaseInvestmentPlanVO> detail(@RequestBody BaseInvestmentPlan baseInvestmentPlan) {
		return baseInvestmentPlanService.getDetailObj(baseInvestmentPlan);
	}

	/**
	 * 分页
	 */
	@PostMapping("/list")
	@ApiOperation(value = "分页")
	public ListResult<BaseInvestmentPlanVO> list(@RequestBody Query query) {
		List<SearchEntity> entityList = query.getSearch();
		if (query.getAscs()==null&&query.getDescs()==null){
			query.setDescs("create_time");
		}
		QueryWrapper<BaseInvestmentPlan> queryWrapper = SearchParamEntiy.getQueryWrapper(
				Condition.getQueryWrapper(new BaseInvestmentPlan()), entityList
		);
		TokenSearch<BaseInvestmentPlan> tokenSearch = new TokenSearch<>();
		tokenSearch.addTokenQuery(queryWrapper, query);

		IPage<BaseInvestmentPlan> pages = baseInvestmentPlanService.page(Condition.getPage(query), queryWrapper);
		List<BaseInvestmentPlanVO> baseInvestmentPlanVOS = baseInvestmentPlanWrapper.entityToVO(pages.getRecords());

		ListResult<BaseInvestmentPlanVO> listResult = new ListResult<>(CommonCode.SUCCESS);
		listResult.setList(baseInvestmentPlanVOS);
		listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
		return listResult;

	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@Resubmit(delaySeconds = 0)
	@LogOperation("投资计划-提交")
	@ApiOperation(value = "新增或修改")
	public ObjResult submit(@Valid @RequestBody BaseInvestmentPlan baseInvestmentPlan) {
		String checkMessage = baseInvestmentPlanService.checkYear(baseInvestmentPlan);
		if (StringUtil.isNotBlank(checkMessage)){
			return new ObjResult(CustomCode.builder().message(checkMessage).code(1999).success(false).build());
		}

		boolean result = baseInvestmentPlanService.submit(baseInvestmentPlan);
		HashMap<String, Object> processVariable = new HashMap<>();
		formWorkflowService.startProcessAndSimulate(String.valueOf(baseInvestmentPlan.getId()),baseInvestmentPlan.getFormType(),processVariable);

		return result ? new ObjResult(CommonCode.SUCCESS) : new ObjResult(CommonCode.FAIL);
	}

	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ApiOperation(value = "删除")
	@LogOperation("投资计划-删除")
	public ObjResult remove(@RequestBody PageData pd) {
		List<String> ids = (List<String>)pd.get("ids");
		return baseInvestmentPlanService.deleteLogic(Func.toLongList(StringUtils.join(ids, StringPool.COMMA)))
				? new ObjResult(CommonCode.SUCCESS) : new ObjResult(CommonCode.FAIL);
	}


	/**
	 * 年度新增投资计划汇总表
	 */
	@PostMapping("/summary")
	@ApiOperation(value = "年度新增投资计划汇总表")
	public ListResult<PageData> summary(@Valid @RequestBody BaseInvestmentPlan baseInvestmentPlan) {

		String checkMessage = baseInvestmentPlanService.checkSummary(baseInvestmentPlan);
		if (StringUtil.isNotBlank(checkMessage)){
			return new ListResult<>(CustomCode.builder().message(checkMessage).code(1999).success(false).build());
		}

		List<InvestmentPlanSummaryVO> results = baseInvestmentPlanService.summary(baseInvestmentPlan.getFilingUnitId(), baseInvestmentPlan.getFilingYear());
		List<PageData> pageDataList = new ArrayList<>();
		try{
			if (CollectionUtil.isNotEmpty(results)){
				for (InvestmentPlanSummaryVO vo : results){
					PageData pd = new PageData();
					ObjectMapper mapper = new ObjectMapper();
					String json = JSON.toJSONStringWithDateFormat(vo, DateUtil.PATTERN_DATETIME);
					pd.putAll(mapper.readValue(json, new TypeReference<HashMap<String,String>>(){}));
					pageDataList.add(pd);
				}
			}
			ListResult<PageData> listResult = new ListResult<>(CommonCode.SUCCESS);
			listResult.setList(pageDataList);
			return listResult;
		} catch (Exception e) {
			log.error(ExceptionUtils.getFullStackTrace(e));
			return new ListResult<>(CommonCode.ERROR);
		}

	}

	/**
	 * 市属国有企业投资计划汇总表
	 */
	@PostMapping("/unitSummary")
	@ApiOperation(value = "市属国有企业投资计划汇总表")
	public ListResult<PageData> unitSummary(@Valid @RequestBody BaseInvestmentPlanDTO baseInvestmentPlanDTO) {
		List<InvestmentUnitSummaryVO> results = baseInvestmentPlanService.unitSummary(baseInvestmentPlanDTO);
		List<PageData> pageDataList = new ArrayList<>();
		try{
			if (CollectionUtil.isNotEmpty(results)){
				for (InvestmentUnitSummaryVO vo : results){
					PageData pd = new PageData();
					ObjectMapper mapper = new ObjectMapper();
					String json = JSON.toJSONStringWithDateFormat(vo, DateUtil.PATTERN_DATETIME);
					pd.putAll(mapper.readValue(json, new TypeReference<HashMap<String,String>>(){}));
					pageDataList.add(pd);
				}
			}
			ListResult<PageData> listResult = new ListResult<>(CommonCode.SUCCESS);
			listResult.setList(pageDataList);
			return listResult;
		} catch (Exception e) {
			log.error(ExceptionUtils.getFullStackTrace(e));
			return new ListResult<>(CommonCode.ERROR);
		}

	}

	/**
	 * 生成excel文件
	 * @param id
	 * @return
	 */
	@GetMapping("/export/{id}")
	@ApiOperation(value = "生成excel文件")
	public ObjResult export(@PathVariable Long id){
		PageData pd = new PageData();
		pd.put("key", baseInvestmentPlanService.export(id));
		ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
		objResult.setPageData(pd);
		return objResult;
	}

	/**
	 * 生成可以导入的excel文件
	 * @param id
	 * @return
	 */
	@GetMapping("/exportImportFile/{id}")
	@ApiOperation(value = "生成可以导入的excel文件")
	public ObjResult exportImportFile(@PathVariable Long id){
		PageData pd = new PageData();
		pd.put("key", baseInvestmentPlanService.exportImportFile(id));
		ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
		objResult.setPageData(pd);
		return objResult;
	}

	/**
	 * 下载excel文件 并删除
	 * @param key
	 * @param response
	 */
	@GetMapping("/download/{key}")
//	@PassToken
	@ApiOperation(value = "下载excel文件 并删除")
	public void download(@PathVariable String key, HttpServletResponse response){
		baseInvestmentPlanService.download(key, response);
	}

	@GetMapping("/exportTemplateExcel")
//	@PassToken
	public void exportTemplateExcel(HttpServletResponse response, OutputStream os){
		baseInvestmentPlanService.exportTemplateExcel(response, os);
	}

	/**
	 * 覆盖导入 根据项目名称覆盖或新增
	 */
	@PostMapping("/excelCoverImport")
	@ApiOperation(value = "覆盖导入 根据项目名称覆盖或新增")
	@LogOperation("投资计划-导入")
	public ObjResult excelCoverImport(@RequestParam("file") MultipartFile multipartFile) throws IOException {
		String progressId = TokenUtil.getTokenUserId() + "_"+System.currentTimeMillis();
		CacheUtil.put("progress","progress",progressId + "#half:hour",0);
		InputStream inputStream = multipartFile.getInputStream();
		baseInvestmentPlanService.importExcel(progressId, inputStream);
		ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
		PageData pd = new PageData();
		pd.put("progressId", progressId);
		objResult.setPageData(pd);
		return objResult;
	}

	/**
	 * 导入进度查看
	 */
	@GetMapping("/progress/{progressId}")
	@ApiOperation(value = "导入进度查看")
	public ObjResult progress(@PathVariable String progressId){
		Object data = CacheUtil.get("progress", "progress", progressId + "#half:hour");
		if(data != null && data instanceof String){
			if ("导入成功".equals(data)){
				ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
				PageData pd = new PageData();
				pd.put("data", 200);
				objResult.setPageData(pd);
				return objResult;
			}
			return new ObjResult(CustomCode.builder().message((String)data).code(1000).success(false).build());
		}
		ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
		PageData pd = new PageData();
		pd.put("data", data);
		objResult.setPageData(pd);
		return objResult;
	}

	/**
	 * 年度项目投资计划柱状图
	 * @param baseInvestmentPlanDTO
	 * @return
	 */
	@PostMapping("/statistics/company")
	@ApiOperation(value = "年度项目投资计划柱状图")
	public R<ChartsVO> statisticsCompany(@RequestBody BaseInvestmentPlanDTO baseInvestmentPlanDTO) {
		R<ChartsVO> result = new R<>(CommonCode.SUCCESS);
		result.setPageData(baseInvestmentPlanService.statisticsCompany(baseInvestmentPlanDTO));
		return result;
	}
}
